#include "RenzoMustHaveGL.h"
#include "RenzoRenderBufferGL.h"
#include "RenzoCamera.h"
#include "RenzoScene.h"
#include "RenzoRenderSystem.h"
#include "RenzoVertexBuffer.h"
#include "RenzoTimer.h"
#include "RenzoDisplay.h"

namespace Renzo
{
RenderBufferGL::RenderBufferGL(void)
{
}

RenderBufferGL::~RenderBufferGL(void)
{
}

void RenderBufferGL::render() {
	//
	// Render 3D
	//

	// 
	// camera ready!
	// 
	
	Camera* c = Renzoderer::instance()->getActiveScene()->getActiveCamera();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0f, 4.0f/3.0f, c->getNearPlane(), c->getFarPlane());

	Float3 eye = c->getEye();
	Float3 lookat = c->getLookat();
	Float3 up = c->getUp();

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(eye.x, eye.y, eye.z, lookat.x, lookat.y, lookat.z, up.x, up.y, up.z);
	
	//
	// Polygon mode
	//
	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	//glEnable(GL_TEXTURE_2D);

	//
	// Render 3D
	//
	// Stage 0: clear vertex buffer
	Renzoderer::instance()->getActiveRenderSystem()->getVertexBuffer()->clear();
	
	// Stage 1: ask scene graph to pass all geometry to vertex buffer (still in CPU)
	Renzoderer::instance()->getActiveScene()->copyToHardware();

	// Stage 2: copy vertex buffer to GPU
	Renzoderer::instance()->getActiveRenderSystem()->getVertexBuffer()->copyToHardware();

	// Stage 3: draw from GPU
	Renzoderer::instance()->getActiveRenderSystem()->getVertexBuffer()->render();


	//
	// Render 2D (overlay GUI)
	//
	int winWidth = Renzoderer::instance()->getWindowWidth();
	int winHeight = Renzoderer::instance()->getWindowHeight();

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0.0, winWidth, 0.0, winHeight);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// draw frame rate
	char strFps[256];
	sprintf(strFps, "%.2f", Renzoderer::instance()->getTimer()->GetAverageFps());
	drawText(0, 0, strFps);
}

void RenderBufferGL::drawText(int x, int y, char *str) {
	glPushAttrib(GL_ENABLE_BIT);
		glDisable(GL_TEXTURE_2D);
		glDisable(GL_DEPTH_TEST);
		
		int len = strlen(str);
		
		glColor3f(0, 0, 0); //black
		glRasterPos2i(x+1, y+1);		
		for (int i = 0; i < len; i++) {
			//Draw		
			glutBitmapCharacter(GLUT_BITMAP_8_BY_13, str[i]);
		}
		
		glColor3f(1, 1, 1); //white
		glRasterPos2i(x, y);				
		for (int i = 0; i < len; i++) {
			//Draw		
			glutBitmapCharacter(GLUT_BITMAP_8_BY_13, str[i]);
		}
				
		
	glPopAttrib();
}
}

